package mammuthus.web.action

import javax.servlet.http.HttpServletRequest
import mammuthus.web.service.{AsyncHelperTrait, SlaveService}
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.{RequestParam, RequestMethod, RequestMapping}

import scala.collection.JavaConversions._
import mammuthus.web.bean.SlaveBean
import org.slf4j.LoggerFactory
import net.liftweb.{json => SJSon}


@Controller()
class ConfAction extends ActionHelperTrait with AsyncHelperTrait {

  val logger = LoggerFactory.getLogger(classOf[ConfAction])
  @Autowired
  val slaveService: SlaveService = null


  @RequestMapping(Array("/conf/addHost.html"))
  def confLink(req: HttpServletRequest,
               @RequestParam(value = "appName", defaultValue = "") appName: String
                ) = {
    val params = putToReqAttribute(req)
    val vappName  = if(appName == "") params("path").split("/").last else appName
    val hosts = if (params.contains("hosts")) params("hosts").split(",").toList else List()
    val hostNames = slaveService.appSlave(vappName)
    req.setAttribute("slaves", (hostNames -- hosts).mkString(","))
    req.setAttribute("in", hosts.mkString(","))
    req.setAttribute("all", hostNames.mkString(","))
    req.setAttribute("appName", vappName)
    "confLink"
  }

  @RequestMapping(value = Array("/conf/confLink.html"), method = Array(RequestMethod.POST))
  def confLinkPost(req: HttpServletRequest,
                   @RequestParam(value = "appName", defaultValue = "") appName: String,
                   @RequestParam(value = "slaves", defaultValue = "") slaves: String,
                   @RequestParam(value = "confPath", defaultValue = "") confPath: String
                    ) = {
    val params = putToReqAttribute(req)
    val shellResult = slaveService.addConfSystem(appName, slaves, confPath,params)
    nav(req, shellResult,
      prePath = (s"#", ""),
      nextPath = (s"/conf/list.html", "去配置系统")
    )
    "shellCommandExecuteResult"
  }


}
